#include "tasksmanager.h"
#include <optra/common/proxy.h>
#include "task.h"
#include <QCoreApplication>
#include <QUuid>

#include "applicationnative.h"
#include "applicationscript.h"

extern Optra::Proxy* proxy;

TasksManager::TasksManager(Application* app, QObject *parent) :
    QObject(parent), app_(app)
{
    qRegisterMetaType<Optra::LogEvent::LogType>("Optra::LogEvent::LogType");
}

TasksManager::~TasksManager()
{
    foreach(Task* t, tasks_.values()){
        t->quit();
        t->wait(2000);
        t->terminate();
        //delete t;
    }

    tasks_.clear();
}

void TasksManager::startApplication(const QString& name)
{
    Task* t = new ApplicationNative(name, app_, proxy->mainZone());
    //Task* t = new ApplicationScript("test", proxy->mainZone());

    connect(t, SIGNAL(finished()), SLOT(taskfinished()));
    connect(t, SIGNAL(state(const QString& , Optra::LogEvent::LogType)), SLOT(taskState(const QString& , Optra::LogEvent::LogType)));

   // tasks_.append(t);
   // t->start();
    //t->run();
}


void TasksManager::taskStarted()
{

}

void TasksManager::taskTermintated()
{

}

void TasksManager::taskState(const QString& message, Optra::LogEvent::LogType type)
{
    QCoreApplication::postEvent(proxy->mainZone(), new Optra::LogEvent(message, type, proxy->mainZone()));
}

void TasksManager::taskfinished()
{
    Task* t = (Task*)sender();
    proxy->mainZone()->debug(QString("task finished %1").arg(t->id()));
    tasks_.remove(t->id());
    delete t;
}


void TasksManager::startTask(Task* task)
{
    Q_ASSERT(task);

    if (task == 0)
        return;

    task->id(QUuid::createUuid().toString());
    proxy->mainZone()->debug(QString("start task %1").arg(task->id()));
    connect(task, SIGNAL(finished()), SLOT(taskfinished()));
   // connect(task, SIGNAL(state(const QString& , Optra::LogEvent::LogType)), SLOT(taskState(const QString& , Optra::LogEvent::LogType)));

    tasks_.insert(task->id(), task);
    task->start();
}
